﻿Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Configuration

Partial Class TakeQuiz
    Inherits System.Web.UI.Page
    Private connectionString As String = WebConfigurationManager.ConnectionStrings("Database").ConnectionString
    Dim numCorrect As Double
    Dim questionLayout As New DataTable
    Dim questionsDataSet As New DataSet
    Dim questionTotal As New Double
    Dim questionLabel As New Label
    Dim answers As New RadioButtonList


    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If IsPostBack = False Then
            userNameHiddenField.Value = CType(PreviousPage.FindControl("userNameHiddenField"), HiddenField).Value
            userNameLabel.Text = CType(PreviousPage.FindControl("userNameHiddenField"), HiddenField).Value.ToString
            quizTitleLabel.Text = CType(PreviousPage.FindControl("titleHiddenField"), HiddenField).Value.ToString
            quizAuthor.Text = CType(PreviousPage.FindControl("ownerNameHiddenField"), HiddenField).Value.ToString
            fillQuestions()
        End If
    End Sub


    Protected Sub fillQuestions()
        'Fills the questionTable with the questions and answers.

        Dim quizID As String = CType(PreviousPage.FindControl("quizIDHiddenField"), HiddenField).Value
        'questionLayout.Columns(
        Dim myConnection As New SqlConnection(connectionString)
        questionLayout = getQuestionIDs(quizID)
        Dim selectQuiz As String = "SELECT question_Id, Question FROM QuestionSelect WHERE Quiz_Id = '" & quizID & "'"
        'Dim question_Id As DataColumn
        'question_Id = questionLayout.PrimaryKey
        myConnection.Open()
        Dim myDataAdapter As New SqlDataAdapter(selectQuiz, myConnection)
        myDataAdapter.Fill(questionLayout)
        myConnection.Close()

        'For index As Integer = 1 To getAmountOfQuestions(CInt(quizID))
        For index As Integer = 1 To questionLayout.Rows.Count - 2
            'Constructors for the dynamic quiz layout
            Dim selectSQL As String = "SELECT question_Id FROM QuestionSelect WHERE Quiz_Id = '" & quizID & "'"

            Dim questionCell As New TableCell
            Dim answerCell As New TableCell
            Dim questionRow As New TableRow
            Dim answerRow As New TableRow
            Dim questionID As DataRow = questionLayout.Rows(index - 1)
            Dim myCommand As New SqlCommand(selectSQL.ToString, myConnection)
            Dim myReader As SqlDataReader
            'Dim qID As Integer = 

            'Creates question label
            Dim labelName As String
            labelName = "question" + index.ToString() + "Label"
            questionLabel.ID = labelName
            questionLabel.Text = getQuizQuestions(questionID.Item(0))
            questionLabel.Text = "<b></br></br>" & questionLabel.Text & "</br></b>"
            questionCell.Controls.Add(questionLabel)

            'Creates the radio button list for all the answers in the question
            Dim answerRblName As String
            answerRblName = "question" & index.ToString() & "RadioButtonList"
            answers.ID = answerRblName
            Dim quizAnswers As DataTable = New DataTable()
            quizAnswers = getQuizAnswers(questionID.Item(0))
            For answerCount As Integer = 0 To quizAnswers.Rows.Count - 1
                answers.Items.Add(quizAnswers.Rows(answerCount)(0).ToString())
            Next

            'Actually displays what was made
            answerCell.Controls.Add(answers)
            questionRow.Cells.Add(questionCell)
            questionTable.Rows.Add(questionRow)
            answerRow.Cells.Add(answerCell)
            questionTable.Rows.Add(answerRow)
        Next
        Session("questionTable") = questionTable
    End Sub

    Protected Function getQuizQuestions(ByVal questionID As Integer) As String
        Dim myConnection As New SqlConnection(connectionString)
        Dim selectSQL As String = "SELECT Question FROM QuestionSelect WHERE Question_ID = " & questionID
        Dim sqlCommand As SqlCommand = New SqlCommand(selectSQL, myConnection)
        myConnection.Close()
        myConnection.Open()
        Dim quizQuestion As String = sqlCommand.ExecuteScalar()
        myConnection.Close()
        Return quizQuestion

    End Function

    Protected Function getAmountOfQuestions(ByVal quizID As Integer) As Integer
        Dim myConnection As New SqlConnection(connectionString)
        Dim selectSQL As String = "SELECT * FROM QuestionSelect WHERE Quiz_Id = '" & quizID & "'"
        Dim myCommand As New SqlCommand(selectSQL.ToString, myConnection)
        Dim quizLengthDatatable As DataTable = New DataTable()

        myConnection.Open()
        Dim questionDataAdapter As New SqlDataAdapter(selectSQL, myConnection)
        questionDataAdapter.Fill(quizLengthDatatable)
        myConnection.Close()
        Return quizLengthDatatable.Rows.Count - 1

    End Function

    '' Need a method that pulls all questions for a quiz based on the Quiz_id,
    '' Then have them be placed into a dataset that will then be the questionID in the getQuizQuestions

    Protected Function getQuestionIDs(ByVal quizID As String) As DataTable
        Dim myConnection As New SqlConnection(connectionString)
        Dim selectSQL As String = ("SELECT question_id FROM QuestionSelect WHERE Quiz_Id = '" & quizID & "'")
        Dim questionIDDatatable As DataTable = New DataTable()
        myConnection.Open()

        Dim questionDataAdapter As New SqlDataAdapter(selectSQL, myConnection)
        questionDataAdapter.Fill(questionIDDatatable)

        myConnection.Close()
        Return questionIDDatatable
    End Function

    'Protected Function getQuizQuestions(ByVal quizID As String, ByVal questionID As String) As String
    '    Dim question As String = ""
    '    Dim selectSQL As String = ("SELECT Question FROM QuestionSelect WHERE Quiz_Id = '" & quizID _
    '                               & "' AND question_Id = '" & questionID & "'")
    '    Dim myConnection As New SqlConnection(connectionString)
    '    Dim myCommand As New SqlCommand(selectSQL.ToString, myConnection)
    '    Dim myReader As SqlDataReader
    '    Dim quizQuestionsDataTable

    '    myConnection.Open()
    '    Dim questionDataAdapter As New SqlDataAdapter(selectSQL, myConnection)
    '    questionDataAdapter.Fill(quizQuestionsDataTable)
    '    myReader = myCommand.ExecuteReader()
    '    myReader.Read()
    '    question = myReader("Question").ToString
    '    myConnection.Close()
    '    Return question
    'End Function

    Private Function getQuizAnswers(ByVal questionID As Integer) As DataTable
        Dim selectSQL As String = "SELECT Answer FROM Answers WHERE questionID = '" & questionID & "'"
        Dim myConnection As New SqlConnection(connectionString)
        Dim questionAnswersDataTable As DataTable = New DataTable()
        myConnection.Open()

        Dim answersDataAdapter As New SqlDataAdapter(selectSQL, myConnection)
        answersDataAdapter.Fill(questionAnswersDataTable)

        myConnection.Close()
        Return questionAnswersDataTable
    End Function

    Protected Sub submitAnswersButton_Click(sender As Object, e As EventArgs) Handles submitAnswersButton.Click
        Dim numCorrect As Integer = checkScore()
        Dim quizID As String = CType(PreviousPage.FindControl("quizIDHiddenField"), HiddenField).Value

        Dim score As Integer = numCorrect / getAmountOfQuestions(CInt(quizID))

        submitAnswersButton.Visible = False
        resultLabel.Text = "You recieved a score of <b>" & score.ToString & "%</b> on this quiz."


        '' Maroney stuff
        'INSERTING INTO TAKENBY TABLE
        'THIS IS FOR TAKE QUIZ PAGE NTO HERE
        Dim insertSQL As New StringBuilder
        insertSQL.Append("INSERT INTO QuizTaken(quizTaken_Id,User_Id,userName)")
        insertSQL.Append("VALUES (@quizTaken_Id,@User_Id,@userName)")

        Dim myConnection As New SqlConnection(connectionString)
        Dim myCommand As New SqlCommand(insertSQL.ToString, myConnection)
        'we must connect parameters to the firls using myCommand.Parameters

        With myCommand.Parameters
            .AddWithValue("@QuizTaken_Id", quizIDHiddenField.Value)
            .AddWithValue("@User_Id", userIDHiddenField.Value)
            .AddWithValue("@userName", userNameHiddenField.Value)


        End With
        Dim successBoolean As Boolean = True

        Try
            myConnection.Open()
            successBoolean = myCommand.ExecuteNonQuery
        Catch ex As Exception
            successBoolean = False
            errorLabel.Text = "Error inserting Question. " & ex.Message
        Finally
            myConnection.Close()
        End Try
    End Sub

    Protected Function checkScore() As Integer
        Dim quizID As String = CType(PreviousPage.FindControl("quizIDHiddenField"), HiddenField).Value
        For index As Integer = 1 To getAmountOfQuestions(CInt(quizID))
            Dim radioButtonName As String
            radioButtonName = "question" + index.ToString() + "RadioButtonList"
            Dim questionTable As Table = Session("questionTable")
            Dim answerRBL As RadioButtonList = questionTable.FindControl(radioButtonName)
            Dim questionID As String

            Dim questionName As String = "question" + index.ToString + "Label"
            Dim questionlabel As Label = questionTable.FindControl(questionName)

            Dim selectQuestionID As String = "SELECT question_id FROM QuestionSelect WHERE Question = '" & questionlabel.Text.ToString & "'"
            Dim myConnection As New SqlConnection(connectionString)
            Dim myCommand As New SqlCommand(selectQuestionID, myConnection)
            myConnection.Close()
            myConnection.Open()
            Dim myReader As SqlDataReader = myCommand.ExecuteScalar()

            questionID = myReader.Read().ToString
            myConnection.Close()

            Dim correctAnswer As DataTable = New DataTable()
            correctAnswer = getCorrectAnswer(questionID)
            For correct As Integer = 1 To correctAnswer.Rows.Count
                If (answerRBL.SelectedValue = correctAnswer.Rows(correct - 1)("Answer").ToString()) Then
                    numCorrect = numCorrect + 1
                End If
            Next
        Next
        questionTable.Rows.Clear()
        submitAnswersButton.Visible = False
        Return numCorrect
    End Function

    ' Next to do - Check to see if the questions are right
    '   do this by FindControl(radioButtonName) and check if the selected index is correct
    '   within the for loop and create a value for each correct,
    '   divide that by whatever the total # of questions is.

    ' Get the home button to work.
    ' show the score in the label after hiding everything.

    Private Function getCorrectAnswer(questionID As String) As DataTable
        Dim selectSQL As String = "SELECT ANSWER FROM Answers WHERE questionID = '" & questionID & "' AND Correct = '1'"
        Dim answerDataTable As DataTable = New DataTable()
        Dim myConnection As New SqlConnection(connectionString)
        myConnection.Close()
        myConnection.Open()
        Dim myAdapter As New SqlDataAdapter(selectSQL, myConnection)
        myAdapter.Fill(answerDataTable)
        myConnection.Close()
        Return answerDataTable
    End Function

End Class
